package org.reenscape.auth;
import org.reenscape.*;
import org.reenscape.model.*;
import org.reenscape.lib.*;
import java.sql.*;
import java.io.*;
/**
* Checks validity of login. Username and passwords, bans, locked, world switching, etc.
* @author Jim
* @version 1.5
*/
public class LoginAuth {


						/**
						* Checks for password validity, world switching, locked accounts, bans, and anything else of that nature, and returns a return code thats sent back to the client.
						* @author Jim
						*/
						public static int Check(PacketParser p3, String playerName, String host, String playerPassword){
							boolean CorrectPassword = false;
							boolean UserBanned = false;
							boolean IPBanned = false;
							int World = 0;
							int Locked = 0;
							int loggedIn = 0;
							long hash = 0L;
							try {	
								ResultSet rs = MySQL.query("SELECT * from `general` WHERE `username` = '"+playerName+"'");
								rs.last();
								int rowOne = rs.getRow();
								if(rowOne == 0) CorrectPassword = false;
								while(rs.last()){
									String dbuser = rs.getString("username");
									String dbpass = rs.getString("password");
									World = rs.getInt("world");
									Locked = rs.getInt("locked");
									loggedIn = rs.getInt("lin");
									hash = rs.getLong("hash");
									if(dbpass.equalsIgnoreCase(playerPassword)) CorrectPassword = true;
									if(!dbpass.equalsIgnoreCase(playerPassword)) CorrectPassword = false;
									break;
								}

							int UserbanPtr = MySQL.count("SELECT COUNT(*) FROM `[A]Userbans` WHERE `username` = '"+playerName+"'");
							if(UserbanPtr > 0) return 4;
						  
							int IPBanPtr = MySQL.count("SELECT COUNT(*) FROM `[A]IPbans` WHERE `address` = '"+host+"'");
							if(IPBanPtr > 0) return 26;
							
							if(CorrectPassword == true && (World != Configuration.WorldID)){
								MySQL.update("UPDATE `general` SET `world` = '"+Configuration.WorldID+"' WHERE `username` = '"+p3.playerName+"'");
								return 21;
							}
							else if(CorrectPassword == true && (World == Configuration.WorldID) && Locked != 0) return 18;
							else if(CorrectPassword == true && (World == Configuration.WorldID) && loggedIn == 0){
								MySQL.update("UPDATE `general` SET `hash` = '"+Library.mutil.playerNameToLong(p3.playerName)+"', `lin` = '1' WHERE `username` = '"+p3.playerName+"'");
								return 2; }
							else if(loggedIn == 1) return 5;
							else if(CorrectPassword == false) return 3;
							else System.out.println("Unhandled login case!");							
						
							} 
							catch (Exception e){
								e.printStackTrace();
							}
						return 8; // Loginserver offline
						}
}